package com.zhongfeng.api.modules.front.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhongfeng.api.modules.customer.vo.CustomerVo;
import com.zhongfeng.api.modules.end.mapper.EndMapper;
import com.zhongfeng.api.modules.end.vo.EndVo;
import com.zhongfeng.api.modules.end.vo.params.EndParams;
import com.zhongfeng.api.modules.front.mapper.FrontMapper;
import com.zhongfeng.api.modules.front.service.FrontService;
import com.zhongfeng.api.modules.front.vo.FrontVo;
import com.zhongfeng.api.modules.front.vo.NumberVo;
import com.zhongfeng.api.modules.front.vo.params.FrontParams;
import com.zhongfeng.api.modules.ip.mapper.IpMapper;
import com.zhongfeng.api.modules.utils.function.Check;
import com.zhongfeng.api.modules.utils.function.Transfer;
import com.zhongfeng.api.modules.utils.pojo.PageDataInfo;
import com.zhongfeng.api.modules.utils.pojo.Result;
import com.zhongfeng.api.modules.utils.service.HttpStatus;
import com.zhongfeng.api.modules.utils.service.ReturnCodes;
import com.zhongfeng.api.modules.utils.service.ReturnMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.*;

import static com.zhongfeng.api.modules.utils.function.Check.isNumeric;

/**
 * @author blueCat
 * @date 2023/2/2 14:02
 * @motto life is a gift
 */
@Service
@Slf4j
public class FrontServiceImpl implements FrontService {
    @Autowired
    private FrontMapper frontMapper;

    @Autowired
    private IpMapper ipMapper;

    @Autowired
    private EndMapper endMapper;

    private static Map<Integer, Integer> numberMap;

    private static List<NumberVo> numberVoList;

    private static Map<Integer,List<String>> endVoMap;

    private static Map<Integer,String> endVoInfo;

    /**
     * 查询上游信息
     *
     * @param params
     * @return
     */
    @Override
    public Result queryAllFront(FrontParams params) {
        Page<FrontVo> page = new Page<>(params.getPageNum(), params.getPageSize());
        List<FrontVo> frontVos = frontMapper.queryAllFront(page, params);
        return Result.setSuccess(HttpStatus.SUCCESS, "", new PageDataInfo(page, frontVos));
    }

    /**
     * 查询全部上游IP
     *
     * @param frontIdList
     * @return
     */
    @Override
    public List<String> queryAllFrontIp(List<Integer> frontIdList) {
        return frontMapper.queryAllFrontIp(frontIdList);
    }

    /**
     * 新增上游信息
     *
     * @param params
     * @return
     */
    @Override
    public Result addFront(FrontParams params) {
        //获取自增长id
        Integer frontId = frontMapper.queryId();
        Integer i = frontMapper.addFront(params);
        if (i == 1) {
            //处理A号码
            List<String> numberList = new ArrayList<>();
            if (params.getNumbers() != null && params.getNumbers() != "") {
                ByteArrayInputStream numberStream = new ByteArrayInputStream(params.getNumbers().getBytes(StandardCharsets.UTF_8));
                Scanner sc = new Scanner(numberStream);
                while (sc.hasNextLine()) {
                    String line = sc.nextLine();
                    if (line.contains(",")) {
                        String[] split = line.split(",");
                        for (String s : split) {
                            if (isNumeric(s)) {
                                numberList.add(s);
                            }
                        }
                        break;
                    } else if (line.contains("，")) {
                        String[] split = line.split("，");
                        for (String s : split) {
                            if (isNumeric(s)) {
                                numberList.add(s);
                            }
                        }
                        break;
                    }
                    if (isNumeric(line)) {
                        numberList.add(line);
                    }
                }
                if (numberList != null && numberList.size() > 0) {
                    frontMapper.addANumber(numberList, frontId);
                }
            }
            return Result.setSuccess(HttpStatus.SUCCESS, "添加落地成功！");
        } else {
            return Result.setFail(HttpStatus.FAIL, "添加落地失败！");
        }
    }

    /**
     * 删除上游信息
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteFront(Integer id) {
        int i = frontMapper.deleteFront(id);
        if (i == 1) {
            //删除该上游的全部A号码
            frontMapper.deleteNumber(id);
            return Result.setSuccess(HttpStatus.SUCCESS, "删除上游成功！");
        } else {
            return Result.setFail(ReturnCodes.DELETE_FRONT_FAIL, ReturnMessage.DELETE_FRONT_FAIL);
        }
    }

    /**
     * 修改上游信息
     *
     * @param params
     * @return
     */
    @Override
    public Result updateFront(FrontParams params) {
        if (params.getNumbers() != null && params.getNumbers() != "") {
            //查询全部原有A号
            List<NumberVo> numberVos = frontMapper.queryFrontNumber(params.getId());
            List<String> oldNumber = new ArrayList<>();
            for (NumberVo numberVo : numberVos) {
                oldNumber.add(numberVo.getNumber());
            }
            //获取新增的A号
            List<String> numberList = new ArrayList<>();
            ByteArrayInputStream numberStream = new ByteArrayInputStream(params.getNumbers().getBytes(StandardCharsets.UTF_8));
            Scanner sc = new Scanner(numberStream);
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                if (line.contains(",")) {
                    String[] split = line.split(",");
                    for (String s : split) {
                        if (isNumeric(s)) {
                            numberList.add(s);
                        }
                    }
                    break;
                } else if (line.contains("，")) {
                    String[] split = line.split("，");
                    for (String s : split) {
                        if (isNumeric(s)) {
                            numberList.add(s);
                        }
                    }
                    break;
                }
                if (isNumeric(line)) {
                    numberList.add(line);
                }
            }
            //去掉老号码中有，新号码中没有的号码
            List<Integer> removeIdList = new ArrayList<>();
            for (NumberVo numberVo : numberVos) {
                if (!numberList.contains(numberVo.getNumber())) {
                    removeIdList.add(numberVo.getId());
                }
            }
            if (removeIdList != null && removeIdList.size() > 0) {
                frontMapper.deleteNumberList(removeIdList);
            }
            //添加老号码中没有的，新号码中有的
            if (numberList != null && numberList.size() > 0) {
                numberList.removeAll(oldNumber);
                if (numberList != null && numberList.size() > 0) {
                    frontMapper.addANumber(numberList, params.getId());
                }
            }
        }
        int i = frontMapper.updateFront(params);
        if (i == 1) {
            return Result.setSuccess(HttpStatus.SUCCESS, "修改落地成功！");
        } else {
            return Result.setFail(HttpStatus.FAIL, "修改落地失败！");
        }
    }

    /**
     * 查询全部A路号码
     *
     * @param params
     * @return
     */
    @Override
    public Result queryAllNumber(FrontParams params) {
        Page<FrontVo> page = new Page<>(params.getPageNum(), params.getPageSize());
        List<NumberVo> numberList = new ArrayList<>();
        if (params.getEndId() != null && params.getEndId() != 0) {
            //获取号码id
            EndVo endVo = endMapper.queryOneEnd(params.getEndId());
            //numberType为空时设置为1，代表下载全部号码
            if(params.getNumberType() == null){
                params.setNumberType(1);
            }
            //获取号码id集合
            if (params.getNumberType().equals(2)){
                List<Integer> numberIdList = new ArrayList<>();
                if (endVo.getAccession() != null && !endVo.getAccession().equals("")) {
                    String[] split = endVo.getAccession().split(",");
                    for (String s : split) {
                        numberIdList.add(Integer.parseInt(s));
                    }
                    params.setNumberIdList(numberIdList);
                }
            }else if (params.getNumberType().equals(1)){
                List<Integer> numberIdList = new ArrayList<>();
                if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
                    String[] split = endVo.getNumberId().split(",");
                    for (String s : split) {
                        numberIdList.add(Integer.parseInt(s));
                    }
                    params.setNumberIdList(numberIdList);
                }
            }
        }
        //查询全部号码
        numberList = frontMapper.queryAllNumber(page, params);
        backFillFrequency(numberList);
        return Result.setSuccess(HttpStatus.SUCCESS, "", new PageDataInfo(page, numberList));
    }

    /**
     * 回填次数和对接网关
     * @param numberList
     */
    private void backFillFrequency(List<NumberVo> numberList) {
        if (endVoMap == null || endVoMap.size() == 0){
            endVoInfo = new HashMap<>();
            endVoMap = new HashMap<>();
            List<EndVo> endVoList = endMapper.queryAllEndWithoutPage();
            for (EndVo endVo : endVoList) {
                endVoInfo.put(endVo.getId(),endVo.getCompany());
                String numberId = endVo.getNumberId();
                if (numberId != null && !numberId.equals("")){
                    String[] split = numberId.split(",");
                    List<String> numberIdList = Arrays.asList(split);
                    endVoMap.put(endVo.getId(),numberIdList);
                }
            }
        }
        for (NumberVo numberVo : numberList) {
            int count = 0;
            Integer numberId = numberVo.getId();
            StringJoiner stringJoiner = new StringJoiner(",");
            for (Integer integer : endVoMap.keySet()) {
                List<String> strings = endVoMap.get(integer);
                if (strings.contains(numberId+"")){
                    stringJoiner.add(endVoInfo.get(integer));
                    count ++;
                }
            }
            numberVo.setUsedEnd(stringJoiner.toString());
            numberVo.setTimes(count);
        }

    }

    /**
     * 查询A号码不分页
     *
     * @return
     */
    public List<NumberVo> queryAllNumberWithoutPage(FrontParams params) {
        return frontMapper.queryAllNumberWithoutPage(params);
    }

    /**
     * 查询落地分布
     *
     * @param params
     * @return
     */
    @Override
    public Result queryFrontDistribution(FrontParams params) {
        Page<FrontVo> page = new Page<>(params.getPageNum(), params.getPageSize());
        List<FrontVo> frontVos = frontMapper.queryAllFronts(page, params);
        if (params.getEndId() != null) {
            //查询下对接网关信息
            EndVo endVo = endMapper.queryOneEnd(params.getEndId());
            //获取号码id集合
            List<Integer> numberIdList = new ArrayList<>();
            if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
                String[] split = endVo.getNumberId().split(",");
                for (String s : split) {
                    numberIdList.add(Integer.parseInt(s));
                }
            }
            //查询全部号码
            if (numberMap == null || numberMap.size() == 0) {
                List<NumberVo> numberVoList = frontMapper.queryAllNumberInfo();
                //将号码id作为键，对应的落地id设为值
                numberMap = new HashMap<>();
                for (NumberVo numberVo : numberVoList) {
                    numberMap.put(numberVo.getId(), numberVo.getFrontId());
                }
            }
            //获取各个落地的号码个数
            //键为落地id，值为号码个数
            Map<Integer, Integer> numberCounts = new HashMap<>();
            for (FrontVo frontVo : frontVos) {
                numberCounts.put(Integer.parseInt(frontVo.getId()), 0);
            }
            //遍历该对接网关的全部号码id
            for (Integer numberId : numberIdList) {
                //获取该号码id对应的落地id
                Integer frontId = numberMap.get(numberId);
                //该落地id对应的号码数加1
                if (numberCounts.get(frontId) != null) {
                    Integer counts = numberCounts.get(frontId) + 1;
                    numberCounts.put(frontId, counts);
                }
            }
            //回填号码个数
            double all = numberIdList.size();
            if (all > 0) {
                for (FrontVo frontVo : frontVos) {
                    frontVo.setNumberCounts(numberCounts.get(Integer.parseInt(frontVo.getId())));
                    //回填百分比
                    double percentage = (frontVo.getNumberCounts() / all) * 100;
                    DecimalFormat df = new DecimalFormat("#0.00");
                    frontVo.setPercentage(df.format(percentage) + "%");
                }
            }
        }
        //回填号码个数和百分比
        return Result.setSuccess(HttpStatus.SUCCESS, "", new PageDataInfo(page, frontVos));
    }

    /**
     * 下载A号码
     *
     * @param params
     * @param resp
     */
    @Override
    public void downloadFile(FrontParams params, HttpServletResponse resp) throws IOException {
        //设置文件名字
        String filename = "ip=";
        //查询下对接网关信息
        if (params.getEndId() != null) {
            EndVo endVo = endMapper.queryOneEnd(params.getEndId());
            filename = URLEncoder.encode(endVo.getCompany(), "UTF-8") + "_" + filename;
            //numberType为空时设置为1，代表下载全部号码
            if(params.getNumberType() == null){
                params.setNumberType(1);
            }
            //获取号码id集合
            if (params.getNumberType().equals(2)){
                filename = URLEncoder.encode("新增号码", "UTF-8")+ "_" + filename;;
                List<Integer> numberIdList = new ArrayList<>();
                if (endVo.getAccession() != null && !endVo.getAccession().equals("")) {
                    String[] split = endVo.getAccession().split(",");
                    for (String s : split) {
                        numberIdList.add(Integer.parseInt(s));
                    }
                    params.setNumberIdList(numberIdList);
                }
            }else if (params.getNumberType().equals(1)){
                List<Integer> numberIdList = new ArrayList<>();
                if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
                    String[] split = endVo.getNumberId().split(",");
                    for (String s : split) {
                        numberIdList.add(Integer.parseInt(s));
                    }
                    params.setNumberIdList(numberIdList);
                }
            }
        }
        List<NumberVo> numberList = frontMapper.queryAllNumberWithoutPage(params);
        String numberStr = "";
        Collections.shuffle(numberList);
        if (params.getDownloadCounts() == null || params.getDownloadCounts().equals(0) || params.getDownloadCounts() > numberList.size()) {
            for (NumberVo numberVo : numberList) {
                numberStr += numberVo.getNumber() + "\n";
            }
        } else {
            int n = params.getDownloadCounts();
            if (n <= numberList.size()) {
                for (int i = 0; i < n; i++) {
                    numberStr += numberList.get(i).getNumber() + "\n";
                }
            }
        }
        if (params.getFrontIdList() == null || params.getFrontIdList().size() == 0) {
            filename += "all";
        } else {
            List<String> ipList = frontMapper.queryAllFrontIp(params.getFrontIdList());
            for (String ip : ipList) {
                int last = ip.lastIndexOf(".");
                ip = ip.substring(last + 1);
                filename += (ip + "&");
            }
            filename = filename.substring(0, filename.length() - 1);
        }
        if (params.getNumber() != null && !params.getNumber().equals("")) {
            filename += ("_prefix=" + params.getNumber());
        }
        if (params.getDownloadCounts() != null && !params.getDownloadCounts().equals(0) && params.getDownloadCounts() < numberList.size()) {
            filename += ("_counts=" + params.getDownloadCounts());
        } else {
            filename += ("_counts=" + numberList.size());
        }
        resp.setHeader("filename", filename);
        //转化为文件流
        InputStream numberStream = new ByteArrayInputStream(numberStr.getBytes(StandardCharsets.UTF_8));
        OutputStream outputStream = resp.getOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = numberStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        outputStream.flush();
        outputStream.close();
        numberStream.close();
    }

    /**
     * 对接修改A号码
     *
     * @param params
     * @return
     */
    @Override
    public Result updateNumber(FrontParams params) {
        //1. 查出全部号码对象
        if (numberMap == null || numberMap.size() == 0) {
            List<NumberVo> numberVoList = frontMapper.queryAllNumberInfo();
            //将号码id作为键，对应的落地id设为值
            numberMap = new HashMap<>();
            for (NumberVo numberVo : numberVoList) {
                numberMap.put(numberVo.getId(), numberVo.getFrontId());
            }
        }
        //2. 查出该对接网关下的全部号码id，并生成id集合
        EndVo endVo = endMapper.queryOneEnd(params.getEndId());
        List<Integer> endNumberIdList = new ArrayList<>();
        if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
            String[] split = endVo.getNumberId().split(",");
            for (String s : split) {
                endNumberIdList.add(Integer.parseInt(s));
            }
        }
        //3. 获取该落地网关下的全部A号码id集合
        List<Integer> frontNumberIdList = new ArrayList<>();
        for (Integer numberId : numberMap.keySet()) {
            if (numberMap.get(numberId).equals(params.getId())) {
                frontNumberIdList.add(numberId);
            }
        }
        //3.1 如果需求号码数大于A号码总数，则设置A号码总数为需求号码数
        if (params.getNumberCounts() > frontNumberIdList.size()) {
            params.setNumberCounts(frontNumberIdList.size());
        }
        //4. 将对接网关中属于该落地网关的号码id提取出来
        List<Integer> frontEndNumberIdList = new ArrayList<>();
        for (Integer numberId : endNumberIdList) {
            if (frontNumberIdList.contains(numberId)) {
                frontEndNumberIdList.add(numberId);
            }
        }
        endNumberIdList.removeAll(frontEndNumberIdList);
        //5. 根据号码数选择新增还是删除
        if (params.getNumberCounts() > frontEndNumberIdList.size()) {
            //5.1 新增号码
            //5.1.1 清除掉与对接网关A号码id集合的交集
            frontNumberIdList.removeAll(frontEndNumberIdList);
            //5.1.2 打乱落地号码id集合，然后给对接id号码集合添加指定数目的号码id
            Collections.shuffle(frontNumberIdList);
            int counts = params.getNumberCounts() - frontEndNumberIdList.size();
            for (int i = 0; i < counts; i++) {
                frontEndNumberIdList.add(frontNumberIdList.get(i));
            }
        } else if (params.getNumberCounts() < frontEndNumberIdList.size()) {
            //5.2 删除号码
            //5.2.1 对接A号码id集合去除掉指定数目
            int counts = frontEndNumberIdList.size() - params.getNumberCounts();
            for (int i = 0; i < counts; i++) {
                frontEndNumberIdList.remove(0);
            }
        }
        //6. 重新拼凑号码id集合字符串，并写入
        String numberIdStr = "";
        endNumberIdList.addAll(frontEndNumberIdList);
        if (endNumberIdList != null && endNumberIdList.size() > 0) {
            for (Integer numberId : endNumberIdList) {
                numberIdStr += (numberId + ",");
            }
            numberIdStr = numberIdStr.substring(0, numberIdStr.length() - 1);
        }
        EndParams endParams = new EndParams();
        endParams.setId(params.getEndId());
        endParams.setNumberId(numberIdStr);
        int i = endMapper.updateEnd(endParams);
        updateFrontDistribution(params.getEndId());
        //更新号码个数
        EndVo endVo1 = endMapper.queryOneEnd(params.getEndId());
        if (endVo1.getNumberId() != null && !endVo1.getNumberId().equals("")) {
            String[] split = endVo1.getNumberId().split(",");
            endMapper.updateEndNumberCounts(endVo1.getId(), split.length);
        }else {
            endMapper.updateEndNumberCounts(endVo1.getId(), 0);
        }
        //7. 返回处理结果
        if (i > 0) {
            return Result.setSuccess(HttpStatus.SUCCESS, "修改号码成功！");
        } else {
            return Result.setFail(HttpStatus.FAIL, "修改号码失败！");
        }
    }

    /**
     * 对接自动分配号码
     *
     * @param params
     * @return
     */
    @Override
    public Result autoUpdateNumber(FrontParams params) {
        if (params.getMaxLines() == null) {
            return Result.setFail(HttpStatus.FAIL, "并发数不能为空！");
        }
        if (params.getMaxLines().equals(0)) {
            EndParams endParams = new EndParams();
            endParams.setId(params.getEndId());
            endParams.setNumberId("");
            int i = endMapper.updateEnd(endParams);
            updateFrontDistribution(params.getEndId());
            EndVo endVo1 = endMapper.queryOneEnd(params.getEndId());
            if (endVo1.getNumberId() != null && !endVo1.getNumberId().equals("")) {
                String[] split = endVo1.getNumberId().split(",");
                endMapper.updateEndNumberCounts(endVo1.getId(), split.length);
            }else {
                endMapper.updateEndNumberCounts(endVo1.getId(), 0);
            }
            if (i > 0) {
                return Result.setSuccess(HttpStatus.SUCCESS, "已清除全部号码！");
            }
        }
        if (params.getFrontGroup() == null) {
            return Result.setFail(HttpStatus.FAIL, "分组不能为空！");
        }
        params.setNumberCounts(params.getMaxLines() / 3);
        //1. 查询全部落地信息,获取总并发数
        List<FrontVo> frontVos = frontMapper.queryAllFrontWithoutPage();
        double totalLines = 0;
        for (FrontVo frontVo : frontVos) {
            if (frontVo.getFrontGroup() != null) {
                if (frontVo.getFrontGroup().equals(params.getFrontGroup())) {
                    totalLines += frontVo.getMaxLines();
                }
            }
        }
        //2. 根据并发比例分配号码
        //分配的号码
        List<Integer> numberIdList = new ArrayList<>();
        for (FrontVo frontVo : frontVos) {
            if (frontVo.getFrontGroup() != null) {
                if (frontVo.getFrontGroup().equals(params.getFrontGroup())) {
                    //2.1 获取分配号码数
                    double maxLines = frontVo.getMaxLines();
                    double percentage = maxLines / totalLines;
                    int counts = (int) (params.getNumberCounts() * percentage);
                    //2.2 查询该落地的全部号码
                    FrontParams frontParams = new FrontParams();
                    List<Integer> frontIdList = new ArrayList<>();
                    frontIdList.add(Integer.parseInt(frontVo.getId()));
                    frontParams.setFrontIdList(frontIdList);
                    List<NumberVo> numberVoList = frontMapper.queryAllNumberWithoutPage(frontParams);
                    //2.3 打乱号码集合并获取前counts个
                    Collections.shuffle(numberVoList);
                    try {
                        for (int i = 0; i < counts; i++) {
                            numberIdList.add(numberVoList.get(i).getId());
                        }
                    } catch (Exception e) {
                        return Result.setFail(HttpStatus.FAIL, "并发超限了！");
                    }
                }
            }
        }
        //3. 更新号码id
        if (numberIdList != null && numberIdList.size() > 0) {
            String numberIdStr = "";
            for (Integer numberId : numberIdList) {
                numberIdStr += (numberId + ",");
            }
            numberIdStr = numberIdStr.substring(0, numberIdStr.length() - 1);
            EndParams endParams = new EndParams();
            endParams.setId(params.getEndId());
            endParams.setNumberId(numberIdStr);
            int i = endMapper.updateEnd(endParams);
            updateFrontDistribution(params.getEndId());
            EndVo endVo1 = endMapper.queryOneEnd(params.getEndId());
            if (endVo1.getNumberId() != null && !endVo1.getNumberId().equals("")) {
                String[] split = endVo1.getNumberId().split(",");
                endMapper.updateEndNumberCounts(endVo1.getId(), split.length);
            }else {
                endMapper.updateEndNumberCounts(endVo1.getId(), 0);
            }
            if (i > 0) {
                return Result.setSuccess(HttpStatus.SUCCESS, "自动分配号码成功！");
            }
        }
        return Result.setFail(HttpStatus.FAIL, "自动分配号码失败！");
    }

    /**
     * 查询全部落地分组
     *
     * @return
     */
    @Override
    public List<Integer> queryFrontGroup() {
        return frontMapper.queryFrontGroup();
    }

    /**
     * 导入A号码
     *
     * @param params
     * @return
     */
    @Override
    public Result importNumber(FrontParams params) {
        //获取全部A号码
        if (numberVoList == null || numberVoList.size() == 0){
            numberVoList = frontMapper.queryAllNumberInfo();
        }
        //获取导入的A号码
        if (params.getNumberString() != null && !params.getNumberString().equals("")) {
            String numberString = params.getNumberString();
            List<Integer> numberIdList = new ArrayList<>();
            if (numberString.contains(",")) {
                String[] split = numberString.split(",");
                List<String> numberList = Arrays.asList(split);
                for (NumberVo numberVo : numberVoList) {
                    if (numberList.contains(numberVo.getNumber())){
                        numberIdList.add(numberVo.getId());
                    }
                }
            } else if (numberString.contains("，")) {
                String[] split = numberString.split("，");
                List<String> numberList = Arrays.asList(split);
                for (NumberVo numberVo : numberVoList) {
                    if (numberList.contains(numberVo.getNumber())){
                        numberIdList.add(numberVo.getId());
                    }
                }
            } else {
                ByteArrayInputStream numberStream = new ByteArrayInputStream(params.getNumberString().getBytes(StandardCharsets.UTF_8));
                Scanner sc = new Scanner(numberStream);
                List<String> numberList = new ArrayList<>();
                while (sc.hasNextLine()) {
                    String line = sc.nextLine();
                    numberList.add(line);
                }
                for (NumberVo numberVo : numberVoList) {
                    if (numberList.contains(numberVo.getNumber())){
                        numberIdList.add(numberVo.getId());
                    }
                }
            }
            //存入号码id集合
            StringJoiner stringJoiner = new StringJoiner(",");
            for (Integer numberId : numberIdList) {
                stringJoiner.add(numberId+"");
            }
            EndParams endParams = new EndParams();
            endParams.setId(params.getEndId());
            endParams.setNumberId(stringJoiner.toString());
            endMapper.updateEnd(endParams);
            updateFrontDistribution(params.getEndId());
            EndVo endVo1 = endMapper.queryOneEnd(params.getEndId());
            if (endVo1.getNumberId() != null && !endVo1.getNumberId().equals("")) {
                String[] split = endVo1.getNumberId().split(",");
                endMapper.updateEndNumberCounts(endVo1.getId(), split.length);
            }else {
                endMapper.updateEndNumberCounts(endVo1.getId(), 0);
            }
            return Result.setSuccess(HttpStatus.SUCCESS, "A号码添加成功");
        } else {
            return Result.setFail(HttpStatus.FAIL, "A号码不能为空");
        }
    }

    /**
     * 新增A号码（新增并发）
     *
     * @param params
     * @return
     */
    @Override
    public Result addNumber(FrontParams params) {
        if (params.getConcurrency() == null) {
            return Result.setFail(HttpStatus.FAIL, "并发数不能为空！");
        }
        if (params.getConcurrency().equals(0)) {
            return Result.setSuccess(HttpStatus.SUCCESS, "新增成功！");
        }
        if (params.getFrontGroup() == null) {
            return Result.setFail(HttpStatus.FAIL, "分组不能为空！");
        }
        params.setNumberCounts(params.getConcurrency() / 3);
        //1. 查询全部落地信息,获取总并发数
        List<FrontVo> frontVos = frontMapper.queryAllFrontWithoutPage();
        double totalLines = 0;
        for (FrontVo frontVo : frontVos) {
            if (frontVo.getFrontGroup() != null) {
                if (frontVo.getFrontGroup().equals(params.getFrontGroup())) {
                    totalLines += frontVo.getMaxLines();
                }
            }
        }
        //查出该对接网关下的全部号码id，并生成id集合
        EndVo endVo = endMapper.queryOneEnd(params.getEndId());
        List<Integer> endNumberIdList = new ArrayList<>();
        if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
            String[] split = endVo.getNumberId().split(",");
            for (String s : split) {
                endNumberIdList.add(Integer.parseInt(s));
            }
        }
        //2. 根据并发比例分配号码
        //分配的号码
        List<Integer> numberIdList = new ArrayList<>();
        for (FrontVo frontVo : frontVos) {
            if (frontVo.getFrontGroup() != null) {
                if (frontVo.getFrontGroup().equals(params.getFrontGroup())) {
                    //2.1 获取分配号码数
                    double maxLines = frontVo.getMaxLines();
                    double percentage = maxLines / totalLines;
                    int counts = (int) (params.getNumberCounts() * percentage);
                    //2.2 查询该落地的全部号码
                    FrontParams frontParams = new FrontParams();
                    List<Integer> frontIdList = new ArrayList<>();
                    frontIdList.add(Integer.parseInt(frontVo.getId()));
                    frontParams.setFrontIdList(frontIdList);
                    List<NumberVo> numberVoList = frontMapper.queryAllNumberWithoutPage(frontParams);
                    //2.3 打乱号码集合
                    Collections.shuffle(numberVoList);
                    try {
                        //获取号码数
                        for (NumberVo numberVo : numberVoList) {
                            if (counts > 0 && (!endNumberIdList.contains(numberVo.getId()))){
                                numberIdList.add(numberVo.getId());
                                counts--;
                            }else if (counts == 0){
                                break;
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                        //return Result.setFail(HttpStatus.FAIL, "并发超限了！");
                    }
                }
            }
        }
        //3. 更新号码id
        if (numberIdList != null && numberIdList.size() > 0) {
            String numberIdStr = "";
            for (Integer numberId : numberIdList) {
                numberIdStr += (numberId + ",");
            }
            String oldNumberId = endVo.getNumberId();
            numberIdStr = numberIdStr.substring(0, numberIdStr.length() - 1);
            EndParams endParams = new EndParams();
            endParams.setId(params.getEndId());
            endParams.setNumberId(oldNumberId + "," + numberIdStr);
            endParams.setAccession(numberIdStr);
            int i = endMapper.updateEnd(endParams);
            updateFrontDistribution(params.getEndId());
            EndVo endVo1 = endMapper.queryOneEnd(params.getEndId());
            if (endVo1.getNumberId() != null && !endVo1.getNumberId().equals("")) {
                String[] split = endVo1.getNumberId().split(",");
                endMapper.updateEndNumberCounts(endVo1.getId(), split.length);
            }else {
                endMapper.updateEndNumberCounts(endVo1.getId(), 0);
            }
            if (i > 0) {
                return Result.setSuccess(HttpStatus.SUCCESS, "新增号码成功！");
            }
        }
        return Result.setFail(HttpStatus.FAIL, "新增号码失败！");
    }

    /**
     * 查询上游属性
     *
     * @return
     */
    @Override
    public Result queryFrontProperty() {
        List<FrontVo> frontVoList = frontMapper.queryFrontProperty();
        return Result.setSuccess(HttpStatus.SUCCESS, "", frontVoList);
    }

    /**
     * 更新落地分布
     */
    public void updateFrontDistribution(Integer endId){
        //查询下对接网关信息
        EndVo endVo = endMapper.queryOneEnd(endId);
        //获取号码id集合
        List<Integer> numberIdList = new ArrayList<>();
        if (endVo.getNumberId() != null && !endVo.getNumberId().equals("")) {
            String[] split = endVo.getNumberId().split(",");
            for (String s : split) {
                numberIdList.add(Integer.parseInt(s));
            }
        }
        //查询全部号码
        if (numberMap == null || numberMap.size() == 0) {
            List<NumberVo> numberVoList = frontMapper.queryAllNumberInfo();
            //将号码id作为键，对应的落地id设为值
            numberMap = new HashMap<>();
            for (NumberVo numberVo : numberVoList) {
                numberMap.put(numberVo.getId(), numberVo.getFrontId());
            }
        }
        List<Integer> frontIdList = new ArrayList<>();
        for (Integer numberId : numberIdList) {
            if (numberMap.get(numberId) != null && !frontIdList.contains(numberMap.get(numberId))){
                frontIdList.add(numberMap.get(numberId));
            }
        }
        String frontIdListStr = Transfer.combineList(frontIdList);
        endMapper.updateFrontDistribution(endId,frontIdListStr);
    }

}
